### Figure A 11 ###

# Load packages 
library(readstata13)
library(ggplot2)
library(dplyr)
library(reshape2)

# Read Replication data 
base <- read.dta13("~/Dropbox/Replication_MVC/Datasets/datasets_analysis/panel_excombatientes.dta", 
                   convert.factors = TRUE, generate.factors = FALSE,
                   encoding = "UTF-8", fromEncoding = NULL, convert.underscore = FALSE,
                   missing.type = FALSE, convert.dates = TRUE, replace.strl = TRUE,
                   add.rownames = FALSE, nonint.factors = TRUE, select.rows = NULL)

base <- base %>%                            
    group_by(codigoespejo) %>%
    dplyr::mutate(laggedval = lag(year, n = 1, default = NA, order_by = year),
                  PONAL_CAPTURES = ifelse(is.na(laggedval), 
                                          NdeCapturasCrucePONAL,diffcaptures),
                  FLAGRANT_CAPTURES = ifelse(is.na(laggedval), 
                                             NdeCapturasenFlagrancia,diffcaptures_f)) %>% 
    dplyr::ungroup()

base <- base %>% 
    dplyr::group_by(codigoespejo) %>% 
    dplyr::mutate(
        PONAL_sum_by_code = sum(PONAL_CAPTURES, na.rm = TRUE),
        Flag_sum_by_code = sum(FLAGRANT_CAPTURES, na.rm = TRUE)) %>% 
    dplyr::ungroup()


GraphreintegrationFLAG <- ggplot (base %>% 
                                      dplyr::group_by(indicedeReintegracion) %>% 
                                      dplyr::summarise(Flag = mean(Flag_sum_by_code, 
                                                                   na.rm = TRUE)), 
                                  aes (x= indicedeReintegracion, y=Flag)) +
    geom_jitter () +
    geom_smooth (method="lm", se=F, col="red") +
    ylab("Mean of Flagrant captures") +
    xlab("Reintegration Index") +
    scale_y_continuous(limits = c(0, 1.5)) +
    #ggtitle("Reintegration Index and Red-handed captures") +
    theme(legend.position='none') 


